package com.helen.ui.bottom;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.helen.adapter.PersonPageAdapter;
import com.helen.db.UserHelper;
import com.helen.entity.LoginRegisterEntity;
import com.helen.entity.PersonPageItem;
import com.helen.event.InfoEnent;
import com.helen.global.Constants;
import com.helen.ui.MainActivity;
import com.helen.ui.account.MoneyListActivity;
import com.helen.ui.account.RechargeActivity;
import com.helen.ui.account.RefreshMoneyUtils;
import com.helen.ui.account.TakeCashActivity;
import com.helen.shopping.R;
import com.helen.ui.BaseFragment;
import com.helen.ui.address.AddressListActivity;
import com.helen.ui.applymerchent.ApplyMerchantActivity;
import com.helen.ui.applymerchent.CheckApplyActivity;
import com.helen.ui.applymerchent.RecoveryAddressListActivity;
import com.helen.ui.coupons.CouponsActivity;
import com.helen.ui.helpordel.HelpOrderActivity;
import com.helen.ui.order.OrderActivity;
import com.helen.ui.recoveryorder.RecoveryOrderActivity;
import com.helen.ui.statistics.StatisticsActivity;
import com.helen.ui.userinfo.UpdateBindPhoneActivity;
import com.helen.ui.userinfo.UserInfoActivity;
import com.helen.utils.ActivityHelper;
import com.helen.utils.ImageLoadUtil;
import com.helen.utils.JsonUtil;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.ShareUtils;
import com.helen.utils.SharedPreferencesUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.UniversalDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.functions.Consumer;

/**
 * Created by yang on 2018/4/15.
 */

public class PersonFragment extends BaseFragment {
    @BindView(R.id.head_image)
    CircleImageView headImage;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_user_balance)
    TextView tvUserBalance;
    @BindView(R.id.tv_take_cash)
    TextView tvTakeCash;
    @BindView(R.id.tv_recharge)
    TextView tvRecharge;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    private static final String[] TITLE = {"我的爱心荣誉证书", "我的订单", "回收订单", "帮助订单", "我的金宝", "我的优惠券", "地址管理", "修改绑定手机", "分享奖等价1元", "客服", "回收地址", "代理申请"};
    private static final int[] IMAGE = {R.mipmap.person_love_icon, R.mipmap.person_order_icon, R.mipmap.person_huishou_icon, R.mipmap.person_help_order_icon, R.mipmap.person_jinbao_icon, R.mipmap.person_counpons_icon, R.mipmap.person_address_icon,
            R.mipmap.person_update_phone_icon, R.mipmap.person_share_icon, R.mipmap.person_customer_icon,
            R.mipmap.sicon_01, R.mipmap.sicon_02};
    private List<PersonPageItem> mDataList = new ArrayList<>();
    private PersonPageAdapter personPageAdapter;
    private LoginRegisterEntity loginRegisterEntity;
    private RxPermissions rxPermissions;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_person;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.person);
        rxPermissions = new RxPermissions(getActivity());
        EventBus.getDefault().register(this);


    }

    @Override
    protected void updateViews() {
        MyLog.e("yang", "PersonFragment");
        initData();
        initAdapter();
    }

    private void initData() {
        for (int i = 0; i < TITLE.length; i++) {
            PersonPageItem item = new PersonPageItem();
            item.setName(TITLE[i]);
            item.setIconId(IMAGE[i]);
            mDataList.add(item);
        }
    }


    private void initAdapter() {
        MyLog.e("yang", "mDataList==" + mDataList.size());
        personPageAdapter = new PersonPageAdapter(R.layout.person_page_item_view, mDataList);
        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.setAdapter(personPageAdapter);
        personPageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (position) {
                    case 0:
                        startActivity(new Intent(getActivity(), StatisticsActivity.class));
                        break;
                    case 1:
                        startActivity(new Intent(getActivity(), OrderActivity.class));

                        break;
                    case 2:
                        startActivity(new Intent(getActivity(), RecoveryOrderActivity.class));

                        break;
                    case 3:
                        startActivity(new Intent(getActivity(), HelpOrderActivity.class));
                        break;
                    case 4:
                        Intent ti = new Intent(getActivity(), MoneyListActivity.class);
                        ti.putExtra("type", 2);
                        startActivity(ti);
                        break;
                    case 5:
                        Intent ti3 = new Intent(getActivity(), CouponsActivity.class);
                        ti3.putExtra("isCheckBox", false);
                        startActivity(ti3);
                        break;
                    case 6:
                        startActivity(new Intent(getActivity(), AddressListActivity.class));
                        break;
                    case 7:
                        Intent ti2 = new Intent(getActivity(), UpdateBindPhoneActivity.class);
                        startActivity(ti2);
                        break;
                    case 8:
                        shareUrl();
//                        ShareUtils.showShare(getActivity(), Constants.APP_API_BASE + Constants.API_SHARE_MOBILE, "善回收", "分享有奖 金宝加1哟!", "");
                        break;
                    case 9:
                        rxPermissions.request(Manifest.permission.CALL_PHONE)
                                .subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(@android.support.annotation.NonNull Boolean aBoolean) throws Exception {
                                        if (aBoolean) {
                                            CallPhoneDialog("4006186010", "", "呼叫", "取消");
                                        } else {
                                            MToast.makeTextShort(getActivity(), "打电话权限拒绝").show();
                                        }
                                    }
                                });
                        break;
                    case 10:
                        startActivity(new Intent(getActivity(), RecoveryAddressListActivity.class));
                        break;
                    case 11:
                        //    1、isApply == false表示没有申请，显示填写资料
                          // 2、isApply == true && result == true 显示申请成功
                        // 3、isApply == true && result == false 显示正在审核中
                        isApplyAgent();


                        break;


                }
            }
        });
    }


    private void isApplyAgent() {
        mMProgressDialog.show();
        HttpParams httpParams = new HttpParams();
        httpParams.put("userId", UserHelper.getInstance().getloginEntity(getActivity()).getId());
        EasyHttp.post(Constants.ISAPPAGENT)
                .baseUrl(Constants.APP_API_BASE2)
                .params(httpParams)
                .execute(new SimpleCallBack<String>() {
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MToast.makeTextLong(getActivity(), getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String s) {
                        int code = JsonUtil.getJsonValuesInt(s, "code");
                        String message = JsonUtil.getJsonValuesString(s, "msg");
                        if (code == 0) {
                            boolean isApply = JsonUtil.getJsonValuesBoolean(s, "isApply");
                            boolean result = JsonUtil.getJsonValuesBoolean(s, "result");
                            if(!isApply){
                                startActivity(new Intent(getActivity(), ApplyMerchantActivity.class));
                            }else {
                                if(result){
                                    startActivity(new Intent(getActivity(),CheckApplyActivity.class).putExtra("type","你已申请成功"));
                                }else {
                                    startActivity(new Intent(getActivity(),CheckApplyActivity.class).putExtra("type","正在为您审核，请稍后…"));
                                }
                            }

                        } else {
                            MToast.makeTextLong(getActivity(), message).show();
                        }
                    }
                });
    }

    private void shareUrl() {
        mMProgressDialog.show();
        HttpParams httpParams = new HttpParams();
        httpParams.put("id", UserHelper.getInstance().getloginEntity(getActivity()).getId());
        EasyHttp.post(Constants.API_JSONAPI_GET_SHARE_URL)
                .params(httpParams)
                .execute(new SimpleCallBack<String>() {
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MToast.makeTextLong(getActivity(), getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String s) {
                        int code = JsonUtil.getJsonValuesInt(s, "code");
                        String message = JsonUtil.getJsonValuesString(s, "msg");
                        if (code == 0) {
                            String url = JsonUtil.getJsonValuesString(s, "url");
                            String QrCodeImg = JsonUtil.getJsonValuesString(s, "QrCodeImg");
                            ShareUtils.showShare(getActivity(), url, "善回收", "分享有奖\n全国免费上门回收旧衣服,电子产品,书籍,家具等各种废旧物品", "");
//                            ShareUtils.showShare(getActivity(),QrCodeImg);
                        } else {
                            MToast.makeTextLong(getActivity(), message).show();
                        }
                    }
                });
    }

    @OnClick({R.id.ll_account_balance, R.id.tv_take_cash, R.id.tv_recharge, R.id.rel_user_info, R.id.tv_exit_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_account_balance:
                Intent ti = new Intent(getActivity(), MoneyListActivity.class);
                ti.putExtra("type", 1);
                startActivity(ti);
                break;
            case R.id.tv_take_cash:
                startActivity(new Intent(getActivity(), TakeCashActivity.class));
                break;
            case R.id.tv_recharge:
                startActivity(new Intent(getActivity(), RechargeActivity.class));
                break;
            case R.id.rel_user_info:
                startActivity(new Intent(getActivity(), UserInfoActivity.class));
                break;
            case R.id.tv_exit_login:
                exitLogin();
                break;

        }
    }

    private void exitLogin() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("退出登录")
                .setMessage("退出后不会删除任何数据,下次登录依然可以使用本账户")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_AUTH_KEY_STORAGE);
                        SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_LOGIN_MODEL);
                        ActivityHelper.getInstance().finishAllActivity();
                        UserHelper.getInstance().setloginEntity(getActivity(), null);
                        UserHelper.getInstance().setIsLogined(false);
                        Intent ti = new Intent(getActivity(), MainActivity.class);
                        startActivity(ti);

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.create().show();
    }

    private void CallPhoneDialog(final String title, String msg, String sure, String cancle) {
        new UniversalDialog(getActivity()).builder().setTitle(title)
//                .setMsg(msg)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:" + title));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);

                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserHelper.getInstance().isLogined()) {
            loginRegisterEntity = UserHelper.getInstance().getloginEntity(getActivity());
            tvUserName.setText(loginRegisterEntity.getName() + "");
//            tvUserBalance.setText(loginRegisterEntity.getMoney() + "");
            ImageLoadUtil.displayImage(mContext, headImage, loginRegisterEntity.getImg(), R.mipmap.icon_person_head, R.mipmap.icon_person_head);

            RefreshMoneyUtils refreshMoneyUtils = new RefreshMoneyUtils();
            refreshMoneyUtils.refreshMoneyApi(getActivity());
            refreshMoneyUtils.setOnResultListener(new RefreshMoneyUtils.OnResultListener() {
                @Override
                public void onResult(double money, int jinbao) {
                    tvUserBalance.setText(money + "");
                }
            });
        }
    }

    @Subscribe
    public void onEventMainThread(InfoEnent event) {
        String msg = event.getmMsg();
        int code = event.getCode();
        MyLog.e("yang", "code=====" + code);
        switch (code) {
            case 1:
                MToast.makeTextLong(getActivity(), msg + "分享成功").show();
                shareApi();
                break;
            case 2:
                MToast.makeTextLong(getActivity(), msg + "分享取消").show();
                break;
            case 3:
                MToast.makeTextLong(getActivity(), msg + "分享失败").show();
                break;
        }


    }

    private void shareApi() {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", UserHelper.getInstance().getloginEntity(getActivity()).getId() + "");
        EasyHttp.post(Constants.API_JSONAPI_SHARE)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MToast.makeTextShort(getActivity(), getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        MyLog.e("yang", "分享金宝加==" + result);
                        String data = PhoneUtils.checkResponseFlag(getActivity(), result, TAG);
                        if (data != null) {
                            MToast.makeTextShort(getActivity(), "金宝加1").show();
                        }

                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
